package com.gxa.email.mq;

import com.gxa.email.dto.MailDTO;
import com.gxa.email.service.EmailService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
@RocketMQMessageListener(consumerGroup = "login-service",topic = "email-code")
public class ConsumerMQ implements RocketMQListener<MailDTO> {

    @Autowired
    private EmailService emailService;

    @Resource(name = "objectRedisTemplate")
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public void onMessage(MailDTO mailDTO) {
        String code = RandomStringUtils.random(4,"0123456789qwertyuiopasdfghjklzxcvbnm");
        mailDTO.setText("你的验证码："+""+code);
        emailService.sendEmail(mailDTO);
        //发送成功后写入redis
        redisTemplate.opsForSet().add("emailCode:"+mailDTO.getTo()[0],code);
        redisTemplate.expire("emailCode:"+mailDTO.getTo()[0], 120, TimeUnit.SECONDS);
    }
}
